package com.gxa.meiye.sso.service.impl;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.gxa.meiye.sso.service.SMService;
import com.gxa.meiye.sso.utils.SendSms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

@Service
//redis操作完成后，自动关闭redis的连接
@Transactional(rollbackFor = Throwable.class)
public class SMServiceImp implements SMService {
    //声明一个常量定义redis中的code的key
    //key:Login_Sms+手机号
    public static final String LOGIN_SMS = "Login_Sms:";

    //绑定redis模板属性
    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Override
    public void sendLoginSms(String phone) throws Exception{
        //一键登录 有没有账号都可以发送短信
        //发送登录 没有注册账号就不行
        //发送注册短信 注册了就不行
        //1.生成验证码(用工具类的静态方法调用)
        String code = SendSms.getMsgCode();
        String templateCode = "SMS_204986028";
        //生成的验证码打印在控制台用于作弊获取
        //System.out.println(code);
        //2.服务器存储验证码并设置失效时间为15分钟分钟
        redisTemplate.opsForValue().set("LOGIN_SMS+phone",code,15,TimeUnit.MINUTES);
        //3.调用工具类发送短信给用户，redis中存储的是json格式的
        String templateParam = "{\"code\":\""+templateCode+"}";
         SendSms.sendSms(phone,templateCode,templateParam);
        // 4. 短信接口返回的数据
        SendSmsResponse response =SendSms.sendSms(phone,templateCode,templateParam);
//       System.out.println("短信接口返回的数据----------------");
//      System.out.println("Code=" + response.getCode()); // OK:成功
//      System.out.println("Message=" + response.getMessage());
//      System.out.println("RequestId=" + response.getRequestId());
//     System.out.println("BizId=" + response.getBizId());


    }

    @Override
    public String sendLoginMessage(String phone) throws Exception {
        String code = SendSms.getMsgCode();
        redisTemplate.opsForValue().set(LOGIN_SMS+phone,code,15,TimeUnit.MINUTES);
        return code;

    }
}
